import axios from "axios";
import { ElNotification } from "element-plus";
import routers from "@/router/index";
const request = axios.create({
  baseURL: "/api",
});
request.interceptors.request.use((config) => {
  if (localStorage.getItem("token")) {
    config.headers.token = localStorage.getItem("token");
  }
  return config;
});
request.interceptors.response.use(
  (data) => {
    if (data.data.token) {
      localStorage.setItem("token", data.data.token);
    }
    return data.data;
  },
  (err) => {
    if (err.response.status == 401) {
      localStorage.removeItem("token");
      routers.push({ path: "/login" });
      ElNotification({
        title: "错误",
        message: "登录过期，请重新登录!",
        type: "error",
      });
    }
    return Promise.reject(err);
  }
);
export default request;
